﻿///<reference path="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" />
///<reference path="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" />
///<reference path="//js/toaster.min.js" />

var AppVersion = 0.1;
var ProgressTableTimeout;
var _mobile = false;
/*
$.ajaxSetup({
    // Disable caching of AJAX responses
    cache: false
});*/

if(sessionStorage.getItem("UnsavedWork") == null)
    sessionStorage.setItem("UnsavedWork", false);

function IsThereUnsavedWork()
{
    return sessionStorage.getItem("UnsavedWork") == "true";
}

function InitializeContentButtons()
{/*
    var buttons = $("#MainContent .my-button");

    $.each(buttons, function ()
    {
        $(this).button(
            {
                icons: { primary: $(this).attr("icon") }
            });
    });*/
}

function InitializeNavButtons()
{
    
    var buttons = $("#NavPanel .button");

    $.each(buttons, function ()
    {       
        $(this).click(function()
            {
      

                $("#NavPanel .button").removeClass("ui-state-highlight");
                $(this).addClass("ui-state-highlight");
                NavigateToPage($(this).attr("navpage"));
            });
    });
    
    if (GetUsername() == null)
        $("#NavPanel .loginrequired").hide();

    
}

function prepHeightToggles()
{
    $(".height-toggle:not(.hasclick)").bind("click", function ()
    {
      
        $(this).toggleClass("small").attr("onclick", "");
        
    }).addClass("hasclick");
}


function NavigateToPage(page)
{
    if (ProgressTableTimeout != null)
        clearTimeout(ProgressTableTimeout);

    

    if (IsThereUnsavedWork())
    {
        //GrowlHighlight("You have unsaved work on this screen.");
        var r = confirm("You have unsaved work on this screen. Do you really want to leave?");
        if (!r)
            return;        
    }
    
    if (typeof PageCleanup == "function")
    {
        PageCleanup();
        PageCleanup = null;
    }



    $("#MainContent").hide();
    $("#MainContent").load(page, function ()
    {
        InitializeContentButtons();
        UnsavedWork(false);
        prepHeightToggles();
        PageReady();
    });
    
}

function prepButtons()
{
   // console.log("prepButtons()")
    $(".my-button").addClass("button").removeClass("my-button");

    $(".button:not(.hasicon").each(function(key, b)
    {
        b = $(b);
        if(b.data("icon"))
            b.addClass("hasicon").prepend("<i class='fa fa-fw " + b.data("icon") + "'></i>");
    });
}

function PageReady()
{
    
    prepButtons();
    $("#MainContent").fadeIn("fast", PrepUiEffects);
    
}


function GetJsonSproc(method, parameters, callback)
{
    //  console.log("GetJsonSproc " + method);
    if (typeof callback == "undefined")
        if (typeof parameters == "function") {
            callback = parameters;
            parameters = {};
        }
    parameters["sproc"] = method;
    DoPost(parameters, callback);
}

function GetJsonMultiResultSproc(method, parameters, callback)
{
    //  console.log("GetJsonSproc " + method);
    if (typeof callback == "undefined")
        if (typeof parameters == "function") {
            callback = parameters;
            parameters = {};
        }
    parameters["multiresultsproc"] = method;
    DoPost(parameters, callback);
}

function GetJsonNonSproc(method, parameters, callback)
{
   // console.log("GetJsonNonSproc " + method);
    parameters["method"] = method;
    DoPost(parameters, callback);    
}

var RestHost = "WebService.aspx";





function DoPost(parameters, callback)
{
    var jqXHR = $.post( RestHost,
      parameters,
      function (res, textStatus, jqXHR)
      {
          if (textStatus == "success")
          {
              callback(res, textStatus);
          }

      },
      "json").fail(function ()
      {
          alert("Error processing\n\n" + jqXHR.responseText);
      });
}

function PrepUiEffects()
{
   // console.log("prep");
    
    $("table.my-table").delegate("tr", "mouseover mouseout", function (e)
    {
        $(this).toggleClass("ui-state-hover");        
    });    
}

function FieldIsEmpty(id)
{
    if ($(id).val() == "")
    {
        $(id).addClass("ui-state-error");
        return true;
    }
    return false;
}

function SelectNotSelcted(id)
{    
    if ($(id + " option:selected").val() == "-1")
    {
        $(id).addClass("ui-state-error");
        return true;
    }
    return false;
}

function Logout()
{
    if(confirm("Logout?"))
    {
        localStorage.removeItem("Username");
        localStorage.removeItem("UserId");
        localStorage.removeItem("pushoverKey");
        localStorage.removeItem("ClientUniqueId");
        document.location.reload();
    }
}

function GetUsername()
{
    return localStorage.getItem("Username");
}

function UserJustLoggedIn()
{
    console.log("UserJustLoggedIn()");
    $("#NavPanel .loginrequired").show();
}

function UpdateLoggedInUserName()
{
    if (GetUsername() != null)
    {
        $("#UsernameSpan").html("<span class='ui-icon ui-icon-person ilb'/>" + GetUsername());
    }
}

function CloseNotify()
{
    $("#NotifyDiv").fadeOut("slow");
}

function Notify(msg)
{
    if (_mobile)
        alert(msg);
    else {
        /*
        $("#NotifyDiv").text(msg);
        $("#NotifyDiv").fadeIn("slow");
        setTimeout(CloseNotify, 2500);
        */
        Growl(msg);
    }

}

function Growl(msg)
{
    var options = {
        themeState: "default"
    };
    ShowGrowl(msg, options);
}

function GrowlHighlight(msg)
{
    if (_mobile)
        alert(msg);
    else {

        var options = {
            themeState: "highlight"
        };
        ShowGrowl(msg, options);
    }
}
function GrowlError(msg)
{
    var options = {
        header: "Error",
        themeState: "error"
    };
    ShowGrowl(msg, options);
}

function ShowGrowl(msg, options)
{
    var mainOptions =
    {
        position: "top-right",
        closeTemplate: "<span class='ui-icon ui-icon-close'/>"
    }
    for (var k in options)
    {
        mainOptions[k] = options[k];
    }

    $.jGrowl(msg,
             mainOptions
             );
}



function selectElementContents(el) {
    var body = document.body, range, sel;
    if (document.createRange && window.getSelection) {
        range = document.createRange();
        sel = window.getSelection();
        sel.removeAllRanges();
        try {
            range.selectNodeContents(el);
            sel.addRange(range);
        } catch (e) {
            range.selectNode(el);
            sel.addRange(range);
        }
    } else if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
}



function UnsavedWork(status)
{
    sessionStorage.setItem("UnsavedWork", status);
}

$.widget("ui.jsontable",
    {
        options:
        {
            source: [],
            showHeader: true,
            sortable: false,
            // hideKeys: [],
            // headerLabels: [],
            // formats: [],
            uidKey: "",
            columnDefs: {},
            columnOrder: [],
            noData: "No data",
            DefaultFormat: "general"
        },
        table: null,

        _setOptions: function (arg)
        {
            var _this = this;
            $.each(arg, function (key, value)
            {
                _this.options[key] = value;
            });
            //alert("setoptions: " + arg);
            //this._superApply();
            this._refresh();
        },

        _setOption: function (key, value)
        {
            //alert("setoption " + key + "\n" + value);
            this.options[key] = value;
            this._refresh();
            //   this._super(key, value);
        },

        _create: function ()
        {
            this._makeNewTable();
            this.element.empty();
            this._refresh();
        },
        _makeNewTable: function ()
        {
            delete this.table;
            this.table = $("<table/>");
            this.table.addClass("ui-jsontable");
        },
        _refresh: function ()
        {
            if (typeof (this.table) != "undefined")
            {
                this.table.detach().empty();
                this._makeNewTable();
            }
            var _table = this.table;
            var _this = this;


            if (this.options.source.length == 0)
            {
                _this.element.text(_this.options.noData).addClass("ui-jsontable-nodata");
                return;
            }
            else
            {
                _this.element.removeClass("ui-jsontable-nodata");
            }


            this.element.addClass("shadow");

            var cols = [];

            if (this.options.columnOrder != null && this.options.columnOrder.length > 0)
            {
                cols = this.options.columnOrder;
             //   console.dir(cols);
                if (cols[cols.length-1] == "_autorest")
                {
                    cols.pop();
                    for (var key in this.options.source[0])
                    {   
                        if(cols.indexOf(key) == -1)
                            cols.push(key);
                    }
                }
            }
            else
            {
                for (var key in this.options.source[0])
                {
                    cols.push(key);
                }
            }


            //alert("in refresh.\n" + this.options.source.length);                 
            if (this.options.showHeader)
            {
                var tr = $("<tr/>").addClass("ui-jsontable-header");

                for (var i = 0; i < cols.length; i++)
                {
                    var key = cols[i];
                    var th = $("<th/>");
                    if (typeof (_this.options.columnDefs) != "undefined" && typeof (_this.options.columnDefs[key]) != "undefined" && typeof (_this.options.columnDefs[key].HeaderText) != "undefined")
                        th.text(_this.options.columnDefs[key].HeaderText);
                    else
                        th.text(key);

                    if (this.options.sortable)
                    {
                        var asc = $("<span class='ui-icon ui-icon-triangle-1-n ilb' title='Sort Ascending'/>");
                        var desc = $("<span class='ui-icon ui-icon-triangle-1-s ilb' title='Sort Descending'/>");

                        var ascwrapper = $("<span>").append(asc);
                        var descwrapper = $("<span>").append(desc);

                        asc.data("key", key).addClass("arrow_asc_" + key);
                        desc.data("key", key).addClass("arrow_desc_" + key);

                        asc.click(function ()
                        {
                            _this._sort("asc", $(this));
                        });

                        desc.click(function ()
                        {
                            _this._sort("desc", $(this));
                        });

                        th.append(ascwrapper).append(descwrapper);

                    }

                    th.appendTo(tr);
                }

                tr.appendTo(_table);
            }

            $.each(this.options.source, function (row, r)
            {
                var tr = $("<tr/>");
                tr.data("row", row);

                if (_this.options.uidKey != "")
                {
                    if (typeof (r[_this.options.uidKey]) != "undefined")
                    {
                        var id = r[_this.options.uidKey];
                        tr.data("uid", id).addClass("ui-jsontable-uid-" + id);
                    }
                }

                for (var i = 0; i < cols.length; i++)
                {
                    // alert(key +"\n" + r[key]);
                    var key = cols[i];
                    var text = r[key];
                    var formatted = text;

                    var td = $("<td/>");

                    if (typeof (_this.options.columnDefs) != "undefined" && typeof (_this.options.columnDefs[key]) != "undefined" && typeof (_this.options.columnDefs[key].Format) != "undefined")
                    {
                        var format = _this.options.columnDefs[key].Format;
                        td.addClass("ui-jsontable-cell-" + format);
                        formatted = _this._formatValue(key, text, r, format);
                    }
                    else
                    {
                        if(_this.options.DefaultFormat == "general")
                            td.addClass("ui-jsontable-cell-general");
                        else
                        {
                            var format = _this.options.DefaultFormat;
                            td.addClass("ui-jsontable-cell-" + format);
                            formatted = _this._formatValue(key, text, r, format);
                        }
                    }



                    td.append(formatted);
                    td.appendTo(tr);
                }
                tr.appendTo(_table);
                //alert(_table.html());
            });
            //alert(this.table.html());
           // this.table.find("th").resizable();
            this.element.empty().append(this.table).removeClass("shadow");
        },
        _sort: function (dir, icon)
        {
            var key = icon.data("key");

            //alert("sort " + key + ", " + dir + ", " + icon);

            if (dir == "desc")
            {

                this.options.source.sort(function (a, b)
                {
                    if (a[key] == b[key]) return 0; // equal no swap
                    if (a[key] > b[key]) return -1;
                    if (a[key] < b[key]) return 1;
                });
            }
            else
            {
                this.options.source.sort(function (a, b)
                {

                    if (a[key] == b[key]) return 0; // equal no swap
                    if (a[key] < b[key]) return -1;
                    if (a[key] > b[key]) return 1;

                });
            }

            this._refresh();


            this.element.find("TH .ui-state-green").removeClass("ui-state-green");
            this.element.find("TH .arrow_" + dir + "_" + key).parent().addClass("ui-state-green");

        },
        _formatValue: function (key, val, row, type)
        {
          //  var type = this.options.columnDefs[key].Format;

            switch (type)
            {
                case "date":
                    {
                        return new Date(val).toLocaleDateString();
                    }
                case "datetime":
                    {
                        if (val == null)
                            return "";

                        return new Date(val).toLocaleString();
                    }
                case "percent":
                    {
                        var n = new Number(val);
                        n *= 100;
                        return n.toFixed(2) + "%";
                    }
                case "number":
                    {
                        return Number(val);
                    }
                case "lat":
                    {
                        return ParseDecimalLatToDegMin(val);
                    }
                case "lon":
                    {
                        return ParseDecimalLonToDegMin(val);
                    }
                    
                case "boolean":
                    {
                        if (val == null) return "";

                        if(val)
                            return "<i class='fa fa-fw fa-check green'></i>";
                        else {
                            return "<i class='fa fa-fw fa-times red'></i>";
                        }
                    }

                case "booleanyn":
                    {
                        if (val == null) return "";

                        if (val)
                            return "<span class='green'>Y</span>";
                        else
                            return "<span class='red'>N</span>"
                        break;
                    }

                case "threeway":
                    {
                        if(val == null) return "";

                        switch (val)
                        {
                            case 0: { return "<span class='red'>0</span>"; break;}
                            case 1: { return "<span class='orange'>1</span>"; break;}
                            case 2: { return "<span class='green'>2</span>"; break;}

                        }
                        break;
                    }


                case "commandblock":
                    {
                        var cb = this.options.columnDefs[key];

                        var items = cb.Items;
                        var container = $("<div>");

                        for (var i = 0; i < items.length; i++)
                        {
                            var item = items[i];
                            var actionName = item.ActionName;
                            var elem = $("<i>").addClass(item.Icon).data("actionName", actionName);

                            if (typeof item.Class != "undefined")
                                elem.addClass(item.Class);

                            if (typeof item.ToolTip != "undefined")
                            {
                                elem.attr("title", item.ToolTip).tooltip();
                            }

                            if (typeof cb.ItemEnabled == "function")
                            {
                                if (!cb.ItemEnabled(elem.data("actionName"), row))
                                {
                                    elem.addClass("ui-state-disabled");
                                }
                                else
                                {
                                    elem.click(function ()
                                    {
                                        cb.ItemClick($(this).data("actionName"), row, $(this).parents("tr"));
                                    });

                                    container.append(elem).append(" ");
                                }
                            }
                            else // if funciton not defined, show element
                            {
                                elem.click(function ()
                                {
                                    cb.ItemClick($(this).data("actionName"), row, $(this).parents("tr"));
                                });

                                container.append(elem).append(" ");
                            }

                        }

                        return container;

                    }

                case "function":
                    {
                        var func = (this.options.columnDefs[key].FormatFunction);
                        if (typeof func == "function")
                            return func(val, row);
                        else return val;

                        break;
                    }

                default:
                    {
                        return val;
                    }
            }
        },


        _destroy: function ()
        {

        }
    });





function PrecedingZeroTwoDigits(n)
{
    if (n < 10)
        return "0" + n;
    else return n;
          
}


function cahceDataForPlot() {
    var dataSetId = $("#DataSetSelect > option:selected").val();
    GetJsonSproc("usp_GetObjectsForPlot",
        {
            DataSetId: dataSetId
        },
        function (json) {
            _data = json;
            // plotData(json);
        });

}